<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let person = {
            name: '张三',
            sex: '男',
            age: 18
        }
        let handler = {
            get(target, key) {
                console.log(`有人来读取${key}属性了`);
                console.log(target, key);
                return key in target ? target[key] : undefined
            },
            set(target, key, value) {
                console.log(`有人来设置${key}属性了`);
                // console.log(target, key, value);
                return target[key] = value
            },
            deleteProperty(target, key) {
                console.log(`有人来删除${key}属性了`);
                if (key=='age') throw new Error('不能删除age')
                delete target[key]
                return Reflect.deleteProperty(target, key)
            }
        }
        const p = new Proxy(person, handler)
        //可以撤销的声明方式
        let foo= {
            a:1,
            b:2,
        }
        let handler2 = {
            get(target, key) {
                console.log(`有人来读取${key}属性了`);
                console.log(target, key);
                return key in target ? target[key] : undefined
            },
        }


        let {proxy,revoke} =Proxy.revocable(foo,handler2)
        console.log(proxy.a);
        // revoke() //撤销了代理，代理对象就不可以调用，会抛出异常
        // console.log(proxy.a);
 //Proxy也能监听数组的变化
 let arr =[1,2]
 let handler3 = {
            set(target, key,value) {
                console.log(`有人来修改${key}属性了`);
                return Reflect.set(target,key,value)
            },
        }

        let p3 = new Proxy(arr,handler3)
        p3.push(3)
        console.log(p3);
    </script>
</body>

</html>